package com.guoxin.thread.concurrent.chapter6;

public class ThreadService {

    private Thread executorThread;
    private boolean finished = false;
    public void executor(Runnable runnable) {
        executorThread = new Thread(() -> {
            Thread runner = new Thread(runnable);
            runner.setDaemon(true);
            runner.start();
            try {
                runner.join();
            } catch (InterruptedException e) {
                finished = true;
            }
        });
        executorThread.start();
    }

    public void showdown(long mills){
        long currentTime = System.currentTimeMillis();
        while (!finished){
            if(System.currentTimeMillis()-currentTime>=mills){
                System.out.println("任务超时，需要结束");
                executorThread.interrupt();
                break;
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("执行线程被打断");
                break;
            }
        }
        finished = false;
    }

    public static void main(String[] args) {
        ThreadService service = new ThreadService();
        long start = System.currentTimeMillis();
        service.executor(() -> {
            while(true){}
        });
        service.showdown(5000);
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }
}
